using COC.Debug;
using UnityEngine;
using System.Collections;
using COC.Service;
namespace COC.CEvent
{
		public class CEventDriven:MonoBehaviour
		{
				private  static CSelection SELECTOR;
				private  static CEventDispatcher Dispatcher;
				public   static  string ALIAS_NAME = "event-driver";
				static GameObject go;
				/// <summary>
				/// Init this instance and enable
				/// </summary>
				public void Init (MonoBehaviour m)
				{
                    DebugTool.Log("EVENT DRIVEEN INITIALIZE");
						RegistEventDriven (m);
						RegistComponents ();
				}


				private void RegistEventDriven (MonoBehaviour m)
				{
						go = GameObject.Find (ALIAS_NAME);
						if (go == null) {
								go = new GameObject ();
								go.name = ALIAS_NAME;
								go.tag = ALIAS_NAME;
								go.AddComponent<CEventDriven> ();
						}

						DontDestroyOnLoad (go);
				}
				///init
				private void RegistComponents ()
				{
                    DebugTool.Log("event driven has readied to regist required components");
						SELECTOR = CSelection.Instance ();
						Dispatcher = CEventDispatcher.Instance (SELECTOR);

//			            DontDestroyOnLoad(SELECTOR);
//			            DontDestroyOnLoad(Dispatcher);

				}
                public static CEventDriven getInstance()
                {
                    if(go!=null)
                     return go.GetComponent<CEventDriven>();
                    return null;

                }
				public void RegistService (string serviceName, CEventType type)
				{
						System.Type t = System.Type.GetType (serviceName);
						IService service = (IService)go.AddComponent (t);
                        DebugTool.Log("event driven has readied to regist required service:" + service.serviceName);
						SELECTOR.Regist (service, type);
				}
                public Component getService(string name)
                {
                    if (!name.Equals(""))
                    {
                        return go.GetComponent(name);
                    }
                    return null;
                }
				public void RemoveService (System.Type serviceName)
				{ 
						System.Type t = serviceName;
						if (go == null)
								go = GameObject.Find (ALIAS_NAME);
						IService service = (IService)go.GetComponent (t);
                        Object.Destroy(service);
						SELECTOR.Resign (service);
				}

				public void HandleMessage (CEventHandler handler)
				{
						Dispatcher.Dispatch (handler);
			           
				}

				public int getAvailableServicesCount ()
				{
                    DebugTool.Log("amount of available service:" + SELECTOR.GetSelector().Count);
						return SELECTOR.GetSelector ().Count;
				}
		}

}